package com.headline.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.headline.pojo.User;
import com.headline.service.UserService;
import com.headline.mapper.UserMapper;
import com.headline.utils.JwtHelper;
import com.headline.utils.MD5Util;
import com.headline.utils.Result;
import com.headline.utils.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
* @author Aloha
* @description 针对表【news_user】的数据库操作Service实现
* @createDate 2024-10-05 14:48:53
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtHelper jwtHelper;

    /*
    登录业务
    1、根据账号查询用户对象
    2、如果用户对象为null，查询失败，账号错误，返回501的错误
    3、对比密码，不匹配返回503的错误
    4、根据用户id生成一个token，放入result返回
     */
    @Override
    public Result login(User user) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<User>();
        lambdaQueryWrapper.eq(User::getUsername, user.getUsername());
        User loginUser = userMapper.selectOne(lambdaQueryWrapper);
        if (loginUser == null) {
            return Result.build(null, ResultCodeEnum.USERNAME_ERROR);
        }
        // 对比密码
        if (!StringUtils.isEmpty(user.getUserPwd())
                && MD5Util.encrypt(user.getUserPwd()).equals(loginUser.getUserPwd())) {
            // 密码正确，登录成功
            // 根据用户id生成token
            String token = jwtHelper.createToken(Long.valueOf(loginUser.getUid()));
            // 将token封装到result返回
            Map data = new HashMap();
            data.put("token", token);
            return Result.ok(data);
        }
        // 密码错误
        return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
    }

    /*
    根据token获取用户数据
    1、token是否在有效期
    2、根据token解析userId
    3、根据用户id查询数据
    4、去掉密码，封装result结果返回
     */
    @Override
    public Result getUserInfo(String token) {
        // 判断是否过期，true过期
        boolean expiration = jwtHelper.isExpiration(token);
        // 过期返回错误码
        if (expiration) {
            return Result.build(null, ResultCodeEnum.NOTLOGIN);
        }
        // 没有过期，查询数据
        int userId = jwtHelper.getUserId(token).intValue();
        User loginUser = userMapper.selectById(userId);
        loginUser.setUserPwd("");
        Map<String, Object> data = new HashMap<>();
        data.put("loginUser", loginUser);

        return Result.ok(data);
    }

    /*
    检查用户名是否已经被注册
    查询结果count > 0则已被注册，count = 0则未被注册
     */
    @Override
    public Result checkUserName(String username) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<User>();
        lambdaQueryWrapper.eq(User::getUsername, username);
        Long count = userMapper.selectCount(lambdaQueryWrapper);
        if (count == 0) {
            return Result.ok(null);
        }
        return Result.build(null, ResultCodeEnum.USERNAME_USED);
    }

    /*
    注册
    1、检查用户名是否已经被注册（重复检查，因为第一次检查后可能被其他人注册，所以在这个事务中再次检查一遍）
    2、密码加密处理
    3、账号数据保存
    4、返回结果
     */
    @Override
    public Result regist(User user) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<User>();
        lambdaQueryWrapper.eq(User::getUsername, user.getUsername());
        Long count = userMapper.selectCount(lambdaQueryWrapper);
        if (count > 0) {
            return Result.build(null, ResultCodeEnum.USERNAME_USED);
        }
        String encrypt = MD5Util.encrypt(user.getUserPwd());
        user.setUserPwd(encrypt);
        userMapper.insert(user);
        return Result.ok(null);
    }
}




